package com.lh.lock;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Semaphore;

/**
 * 信号量 Semaphore 主要用于做限流操作，acquire()方法会减一 知道小于等于零时，阻塞其他线程
 *
 *  CountDownLatch 主要用于让一批线程等待另一批线程的执行，直到这批线程执行完才能轮到另一批线程唤醒
 *
 *
 *  CyclicBarrier 会阻塞正在运行的线程，直到所有线程都已经完成阻塞才会唤醒所有的线程
 */
public class MySemaphore {

    public static void main(String[] args) throws InterruptedException {

//        myCountDownLatch();

//        mySemaphore();

//        myCyclicBarrier();




    }

    private static void myCyclicBarrier() {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(5);

        for (int i = 0; i < 5; i++) {
            new Thread(()->{

                try {
                    System.out.println(Thread.currentThread().getName()+"开始执行!");
                    cyclicBarrier.await();
                    System.out.println("必须等到5个线程都执行到await方法后才能开始后续的执行!");
                } catch (Exception e) {
                    e.printStackTrace();

                }
            },i+"").start();

        }
    }

    private static void mySemaphore() {
        Semaphore semaphore = new Semaphore(5);

        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName()+"获得信号量!");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            },""+i).start();
        }
    }

    private static void myCountDownLatch() throws InterruptedException {
        CountDownLatch downLatch = new CountDownLatch(5);

        for (int i = 0; i < 5; i++) {

            new Thread(()->{

                System.out.println(Thread.currentThread().getName()+"进来了!");
                downLatch.countDown();


            },i+"").start();
        }

        downLatch.await();

        System.out.println("5个线程都完成了才轮到我执行!");
    }

}
